package de.rac.vaadin.framework.ui;

import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Button.ClickEvent;
//import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.themes.Runo;
import com.vaadin.ui.Component;
import java.io.Serializable;

/*******************************************************************************
 * Dialog to show a message with 1 or 2 buttons or any detachable form with 1 or 2 buttons<br>
 * @author Volodymyr Dobryvechir (dobrivecher@yahoo.com)
 * @version 0.2 31.05.2012  <br>
 ******************************************************************************/
public class ConfirmDialog extends Window implements Button.ClickListener,Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = -8783435695230326733L;
	Callback callBack;
	Button close,submit;
	public ConfirmDialog(String caption,Object content,String submitMessage,String closeMessage,
			Callback callback,String defWidth,String defHeight){
		super(caption);
		setModal(true);
		this.callBack = callback;
		VerticalLayout l = (VerticalLayout) this.getContent();
		if (defWidth==null && defHeight==null)
		      l.setSizeUndefined();
		if (defWidth!=null) l.setWidth(defWidth);
		if (defHeight!=null) l.setHeight(defHeight);
		this.setStyleName(Runo.WINDOW_DIALOG);
    	HorizontalLayout h = new HorizontalLayout();
    	if (submitMessage!=null)
    	{
           submit=new Button(submitMessage,this);
      	   h.addComponent(submit);
    	}
    	if (closeMessage!=null)
    	{
           close=new Button(closeMessage,this);
    	   h.addComponent(close);
    	}
    	if (content!=null)
    	{
    		Component a=null;
    		if (content instanceof String)
    		{
    	      a = new Label((String)content);
    		}
    		else if (content instanceof Component) a=(Component)content;
    		if (a==null) a=new Label("Error component: "+content);
    	    l.addComponent(a);
    	}
    	l.addComponent(h);
    	this.addListener(new Window.CloseListener() {
			
			private static final long serialVersionUID = 1L;

			@Override
			public void windowClose(CloseEvent e) {
				if (callBack!=null) ;
				    callBack.onDialogResult(false);
			}
		});
	}
    public void closeWindow()
    {
		if (getParent() != null) {
            ((Window) getParent()).removeWindow(this);
        }
    }
	@Override
	public void buttonClick(ClickEvent event) {
		boolean resultIsYes=event.getSource() == submit;
		if (resultIsYes && callBack!=null && !callBack.validateFinish()) return;

		if (callBack!=null)
            callBack.onDialogResult(resultIsYes);
		closeWindow();
	}
	
	 public interface Callback extends Serializable {
		    public boolean validateFinish();
	        public void onDialogResult(boolean resultIsYes);
	    }
	
	

}
